/* eslint-disable */
const path = require('path');

const LARAVEL_DIR = path.resolve(__dirname, '../../public/wx-system/');

require('shelljs/global');
// node 可以这样引入全局变量 ? 用于调用 shell 命令
env.NODE_ENV = 'production';
const ora = require('ora'); // 一个 spinner 的动画
// 载入 webpack( webpackConfig , callback ) 执行编译
const webpack = require('webpack');
const webpackConfig = require('./webpack.prod.config.js');

console.log(' [WARNING] Production Building !!!! \n');

const spinner = ora('building for production...');
spinner.start();

// 清理上次编译的内容, 然后复制 static 静态资源
rm('-rf', LARAVEL_DIR);

// returns a Compiler instance
const compiler = webpack(webpackConfig);

compiler.hooks.compile.tap('panx-watch-plugin', beforeCompile);

compiler.watch({ // watch options:
	aggregateTimeout: 300, // wait so long for more changes
	poll: true, // use polling instead of native watchers
	timings: true, // 显示编译时间?
}, afterCompiled);

function beforeCompile() {
	console.log(`\n开始编译: ${getNowTime()}`);
	// if (compile_count == 2) exit(2);
}

let compile_count = 1;

function afterCompiled(err, stats) {
	spinner.stop();
	if (err) {
		if (err.details) {
			console.error(err.details);
		}
		throw err;
	}

	process.stdout.write(`${stats.toString({
		colors: true,
		modules: false,
		children: false,
		chunks: false,
		chunkModules: false,
	})}\n`);

	console.log(`编译次数 : ${compile_count++}`);
	console.log(`now : ${getNowTime()}`);
}

function getNowTime() {
	return (new Date()).toTimeString().split(' ').shift();
}
